package com.linx.common.translation.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linx.common.translation.annotation.TranslationType;
import com.linx.common.translation.core.TranslationInterface;
import com.linx.common.translation.core.handler.TranslationBeanSerializerModifier;
import com.linx.common.translation.core.handler.TranslationGroupHandler;
import com.linx.common.translation.core.handler.TranslationHandler;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 翻译模块配置类
 *
 * @author Lion Li
 */
@Slf4j
@AutoConfiguration
public class TranslationConfig {

    @Autowired
    private List<TranslationInterface<?>> translationInterfaceList;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 将所有实现了 TranslationInterface 接口的类注入到 TranslationHandler 中，并设置 Bean 序列化修改器
     */
    @PostConstruct
    public void init() {
        Map<String, TranslationInterface<?>> map = new HashMap<>(translationInterfaceList.size());
        for (TranslationInterface<?> translationInterface : translationInterfaceList) {
            if (translationInterface.getClass().isAnnotationPresent(TranslationType.class)) {
                TranslationType annotation = translationInterface.getClass().getAnnotation(TranslationType.class);
                map.put(annotation.type(), translationInterface);
            } else {
                log.warn("{} 翻译实现类未标注 TranslationType 注解!", translationInterface.getClass().getName());
            }
        }
        TranslationHandler.TRANSLATION_MAPPER.putAll(map);
        TranslationGroupHandler.TRANSLATION_MAPPER.putAll(map);
        // 设置 Bean 序列化修改器
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new TranslationBeanSerializerModifier()));
    }

}
